package com.jie.crm.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jie.cache.Caches;
import com.jie.cache.support.CacheDef;
import com.jie.crm.domain.CustomerCondition;
import com.jie.crm.domain.CustomerInfo;
import com.jie.crm.domain.CustomerLoanType;
import com.jie.crm.domain.CustomerSource;
import com.jie.crm.domain.CustomerType;
import com.jie.crm.enumeration.ECustomerState;
import com.jie.crm.repository.CustomerInfoRepository;

import spring.data.jpa.tools.DBHelper;

/**
 * 
 * <br>
 * 时间： 2018年2月27日 下午10:12:19
 * 
 * @author wangjie
 *
 */
@Service
public class CustomerInfoService {
	@Autowired
	private CustomerInfoRepository customerInfoRepository;

	public Page<CustomerInfo> findPage(Map<String, Object> searchParams, Pageable pageable) {
		Page<CustomerInfo> customerPage = DBHelper.bind(customerInfoRepository).findPage(searchParams, pageable);
		if (customerPage.hasContent()) {
			for (CustomerInfo customerInfo : customerPage) {
				converter(customerInfo);
			}
		}
		return customerPage;
	}

	private void converter(CustomerInfo customerInfo) {
		if (customerInfo.getConditionId() != null) {
			CustomerCondition condition = Caches.get(CustomerCondition.class,
					String.valueOf(customerInfo.getConditionId()));
			customerInfo.setCustomerCondition(condition.getConditionName());
		}
		if (customerInfo.getSourceId() != null) {
			CustomerSource source = Caches.get(CustomerSource.class, String.valueOf(customerInfo.getSourceId()));
			customerInfo.setCustomerSource(source.getSourceName());
		}
		if (customerInfo.getTypeId() != null) {
			CustomerType type = Caches.get(CustomerType.class, String.valueOf(customerInfo.getTypeId()));
			customerInfo.setCustomerType(type.getTypeName());
		}
		if (customerInfo.getLoanType() != null) {
			CustomerLoanType type = Caches.get(CustomerLoanType.class, String.valueOf(customerInfo.getLoanType()));
			customerInfo.setLoanTypeName(type.getTypeName());
		}
		if (customerInfo.getState() != null) {
			CacheDef type = Caches.get(ECustomerState.class, customerInfo.getState());
			customerInfo.setState(type.getNameField());
		}
	}

	@Transactional
	public void save(CustomerInfo info) {
		DBHelper.bind(customerInfoRepository).save(info);
	}

	@Transactional
	public void delete(Integer id) {
		DBHelper.bind(customerInfoRepository).deleteById(id);
	}

	public CustomerInfo get(Integer id) {
		CustomerInfo info = DBHelper.bind(customerInfoRepository).get(id);
		converter(info);
		return info;
	}
}
